﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using BusinessLayer.FindArtInfo;
using BusinessLayer.RegInfo;
using BusinessLayer.RegInfo.Entities;
using CommandLib;
using FindArtInfo.Common;
using FindArtInfo.Models;
using OnePay;
using Resources;

namespace FindArtInfo.Controllers
{
    public class AccountController : MultiBase
    {
        [RestoreModelStateFromTempData]
        public ActionResult Login()
        {
            PageLoginModel model = new PageLoginModel();
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult Login(PageLoginModel model)
        {                       
            Account account = new AccountBL().GetByEmail(model.Email);
            if (account == null)
            {
                new LoginLogBL().Insert(new LoginLog
                {
                    Email = model.Email,
                    PassWord = model.PassWord,
                    Ip = Utils.GetPublicIP(),
                    Status = Constants.LoginStatus.ERROR
                });
                ModelState.AddModelError("MessageResult", Multi.PageLoginHomeErrorEmail);
                return Redirect(string.Format("~/{0}/login.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (!account.PassWord.Equals(model.PassWord))
            {
                new LoginLogBL().Insert(new LoginLog
                {
                    Email = model.Email,
                    PassWord = model.PassWord,
                    Ip = Utils.GetPublicIP(),
                    Status = Constants.LoginStatus.ERROR
                });
                ModelState.AddModelError("MessageResult", Multi.PageLoginHomeErrorPass);
                //return View(new PageLoginModel());
                return Redirect(string.Format("~/{0}/login.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (account.Status == Constants.StatusAccount.IS_NOT_ACTIVE)
            {
                ModelState.AddModelError("MessageResult", Multi.PageLoginHomeErrorAccountIsNotActive);
                Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
                return Redirect(string.Format("~/{0}/register-again.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (account.StartDate == null || account.EndDate == null)
            {
                int result;
                new AccountBL().ActiveAccount(account.Id, out result);                
                if (result < 0)
                {                    
                    ModelState.AddModelError("MessageResult", Multi.PageLoginHomeActiveAccountError);
                    //return View(new PageLoginModel());
                    return Redirect(string.Format("~/{0}/login.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
                }
                else
                {
                    //send email
                    //string subject = "Access to FindArtInfo.com";
                    //string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                    //Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, model.Email,
                    //                        model.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                    //end
                }
            }
            account = new AccountBL().GetById(account.Id);
            DateTime dateTimeNow = new CommonBL().GetDateTimeNow();
            TimeSpan timeSpan = Convert.ToDateTime(account.EndDate) - dateTimeNow;
            if (timeSpan.Days < 0)
            {
                Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
                return Redirect(string.Format("~/{0}/renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            Session[Constants.SessionKey.SESSION_USER_LOGIN] = account;
            Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
            new LoginLogBL().Insert(new LoginLog
            {
                Email = model.Email,
                PassWord = model.PassWord,
                Ip = Utils.GetPublicIP(),
                Status = Constants.LoginStatus.SUCCESS
            });
            return Redirect(string.Format("~/{0}/home.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }        

        [CustomAuthorize]
        [RestoreModelStateFromTempData]
        public ActionResult ChangePassWord()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [CustomAuthorize]
        [SetTempDataModelState]
        public ActionResult ChangePassWord(PageChangePassWordModel model)
        {
            Account account = (Account)Session[Constants.SessionKey.SESSION_USER_LOGIN];
            if (!account.PassWord.Equals(model.OldPassWord))
            {
                ModelState.AddModelError("MessageResult", Multi.PageChangePassWordError);
                //return Redirect("~/change-password.html");
                return Redirect(string.Format("~/{0}/change-password.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            account.PassWord = model.NewPassWord;
            new AccountBL().Update(account);
            string subject = "Your Password has been changed";
            string content = string.Format("Dear {0},<p>This email confirms that your password has been changed!</p><p>To log on to the site, use the following credentials:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br></p>", account.LastName, account.Email, account.PassWord);
            Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, account.Email,
                                    account.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
            ModelState.AddModelError("MessageResult", Multi.PageChangePassWordSuccess);
            //return View();
            //return Redirect("~/change-password.html");
            return Redirect(string.Format("~/{0}/change-password.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        private PageRegisterModel InitPageRegisterModel()
        {
            PageRegisterModel model = new PageRegisterModel();
            model.ListCountry = new BusinessLayer.RegInfo.CountryBL().GetAll();
            List<Subscription> listSubscriptions = new SubscriptionBL().GetAll();
            model.ListSubscriptions = listSubscriptions;
            return model;
        }

        [RestoreModelStateFromTempData]
        public ActionResult Register()
        {
            return View(InitPageRegisterModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult Register(PageRegisterModel registerModel)
        {
            //Check thong tin tai khoan
            if (ModelState.IsValid)
            {
                //them moi user            
                Account account = new Account();
                account.FirstName = registerModel.FirstName;
                account.LastName = registerModel.LastName;
                account.Email = registerModel.Email;
                account.PassWord = registerModel.CreatePassWord;
                account.CountryId = registerModel.CountryId;
                account.Status = Constants.StatusAccount.IS_NOT_ACTIVE;
                string couponCode = registerModel.CouponCode != null ? registerModel.CouponCode : string.Empty;
                //id giao dich thanh toan            
                string merchTxnRef = Encrypt.MD5(Guid.NewGuid().ToString());
                double amount;
                long transactionId;
                int result;
                new AccountBL().Insert(account, registerModel.SubscriptionId,
                    registerModel.TypePay, Constants.TypeTransactionPayMent.Register, couponCode, merchTxnRef, out amount, out transactionId, out result);
                if (result > 0)
                {
                    string paramReturnUrl = Encrypt.EncodeTo64(Crypto.EncryptString("#36&()9KJHaq@!ad", merchTxnRef + "#" + transactionId + "#" + Constants.TypeTransactionPayMent.Register));

                    if (registerModel.TypePay == Constants.TypePay.ONE_PAY)
                    {
                        //chuyen giao dich sang ben onepay
                        VPCRequest conn = new VPCRequest(Config.OnePayVitualPaymentClientURL);
                        conn.SetSecureSecret(Config.OnePaySecretKey);
                        conn.AddDigitalOrderField("AgainLink", "http://onepay.vn");
                        conn.AddDigitalOrderField("Title", "Onepay Paygate");
                        conn.AddDigitalOrderField("vpc_Locale", "en");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
                        conn.AddDigitalOrderField("vpc_Version", 2.ToString());
                        conn.AddDigitalOrderField("vpc_Command", "pay");
                        conn.AddDigitalOrderField("vpc_Merchant", Config.OnePayMerchantId);
                        conn.AddDigitalOrderField("vpc_AccessCode", Config.OnePayAccessCode);
                        conn.AddDigitalOrderField("vpc_MerchTxnRef", merchTxnRef);
                        conn.AddDigitalOrderField("vpc_OrderInfo", string.Format("{0} {1}", "Order Info ", transactionId));
                        conn.AddDigitalOrderField("vpc_Amount", (amount * 100).ToString());
                        conn.AddDigitalOrderField("vpc_ReturnURL", string.Format("{0}?p={1}", Config.OnePayUrlReturn, HttpUtility.UrlEncode(paramReturnUrl)));
                        conn.AddDigitalOrderField("vpc_TicketNo", Utils.GetPublicIP());
                        // Chuyen huong trinh duyet sang cong thanh toan
                        string url = conn.Create3PartyQueryString();
                        return Redirect(url);
                    }
                    else
                    {
                        Subscription subscription =
                            new SubscriptionBL().GetBySubscriptionID(registerModel.SubscriptionId);
                        StringBuilder sb = new StringBuilder();
                        sb.Append(Config.PayPalUrl);
                        sb.Append("?");
                        sb.Append(string.Format("cmd={0}", "_xclick"));
                        sb.Append(string.Format("&business={0}", HttpUtility.UrlEncode("contact@findartinfo.com")));
                        sb.Append(string.Format("&item_name={0}", HttpUtility.UrlEncode("Subscription for " + subscription.Title + " (Id: " + transactionId + ")")));
                        sb.Append(string.Format("&item_number={0}", "Signatures"));
                        sb.Append(string.Format("&amount={0}", amount.ToString()));
                        sb.Append(string.Format("&no_shipping={0}", "0"));
                        sb.Append(string.Format("&return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlReturn, paramReturnUrl))));
                        sb.Append(string.Format("&cancel_return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlCancel, paramReturnUrl))));
                        sb.Append(string.Format("&no_note={0}", "0"));
                        sb.Append(string.Format("&currency_code={0}", "USD"));
                        sb.Append(string.Format("&lc={0}", "GB"));
                        sb.Append(string.Format("&bn={0}", "PP-BuyNowBF"));
                        return Redirect(sb.ToString());
                    }
                }
                else
                {
                    switch (result)
                    {
                        case -1:
                            ModelState.AddModelError("MessageResultRegister", Multi.PageRegisterExistsAccount);
                            return Redirect(string.Format("~/{0}/login.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
                        case -2:
                            ModelState.AddModelError("MessageResultRegister", Multi.PageRegisterIsNotExistsSub);
                            break;
                        case -3:
                            ModelState.AddModelError("MessageResultRegister", Multi.PageRegisterAccountIsCreatedByNotPay);
                            break;
                    }
                }
            }
            //return View(InitPageRegisterModel(registerModel.PartnerCode));
            //return Redirect("~/register.html");
            return Redirect(string.Format("~/{0}/register.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        [RestoreModelStateFromTempData]
        public ActionResult ForgotPassword()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult ForgotPassword(PageForgotPasswordModel model)
        {
            Account account = new AccountBL().GetByEmail(model.Email);
            if (account != null)
            {
                string subject = "Access to FindArtInfo.com";
                string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                int result = Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, model.Email,
                                        model.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                ModelState.AddModelError("MessageResult", Multi.PageForgotPassWordSuccess);
            }
            else
            {                
                ModelState.AddModelError("MessageResult", Multi.PageForgotPassWordError);                
            }
            //return View();
            //return Redirect("~/forgot-password.html");
            return Redirect(string.Format("~/{0}/forgot-password.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        [RestoreModelStateFromTempData]
        public ActionResult LoginPaid()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult LoginPaid(PageLoginPaidModel model)
        {
            string email = model.Email;
            string pass = model.PassWord;
            Account account = new AccountBL().GetByEmail(email);
            if (account == null)
            {
                ModelState.AddModelError("MessageResult", Multi.PageLoginPaidMessageEmailIsNotExists);
                //return View();
                //return Redirect("~/login-renew.html");
                return Redirect(string.Format("~/{0}/login-renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (!account.PassWord.Equals(pass))
            {
                ModelState.AddModelError("MessageResult", Multi.PageLoginPaidMessageIncorrectLogin);
                //return View();
                //return Redirect("~/login-renew.html");
                return Redirect(string.Format("~/{0}/login-renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (ModelState.IsValid)
            {
                Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
                return Redirect(string.Format("~/{0}/renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            //return View();
            //return Redirect("~/login-renew.html");
            return Redirect(string.Format("~/{0}/login-renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        public PageReNewModel InitializeReNew()
        {
            Account account = (Account)Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID];
            PageReNewModel reNewModel = new PageReNewModel();
            reNewModel.ListSubscription = new SubscriptionBL().GetAll();
            reNewModel.Email = account.Email;
            return reNewModel;
        }
        
        [CustomAuthorizePaidAttribute]
        [RestoreModelStateFromTempData]
        public ActionResult ReNew()
        {
            return View(InitializeReNew());
        }

        [CustomAuthorizePaidAttribute]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult ReNew(PageReNewModel reNewModel)
        {
            Account account = (Account)Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID];
            //id giao dich thanh toan            
            string merchTxnRef = Encrypt.MD5(Guid.NewGuid().ToString());
            double amount;
            long transactionId;
            int result;
            new TransactionLogBL().Insert(account.Id, reNewModel.SubscriptionId,
                reNewModel.TypePay, Constants.TypeTransactionPayMent.Renew, reNewModel.CouponCode, merchTxnRef, out amount, out transactionId, out result);
            if (result > 0)
            {
                string paramReturnUrl = Encrypt.EncodeTo64(Crypto.EncryptString("#36&()9KJHaq@!ad", merchTxnRef + "#" + transactionId + "#" + Constants.TypeTransactionPayMent.Renew));
                //chuyen giao dich sang ben onepay
                if (reNewModel.TypePay == Constants.TypePay.ONE_PAY)
                {
                    //chuyen giao dich sang ben onepay
                    VPCRequest conn = new VPCRequest(Config.OnePayVitualPaymentClientURL);
                    conn.SetSecureSecret(Config.OnePaySecretKey);
                    conn.AddDigitalOrderField("AgainLink", "http://onepay.vn");
                    conn.AddDigitalOrderField("Title", "Onepay Paygate");
                    conn.AddDigitalOrderField("vpc_Locale", "en");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
                    conn.AddDigitalOrderField("vpc_Version", 2.ToString());
                    conn.AddDigitalOrderField("vpc_Command", "pay");
                    conn.AddDigitalOrderField("vpc_Merchant", Config.OnePayMerchantId);
                    conn.AddDigitalOrderField("vpc_AccessCode", Config.OnePayAccessCode);
                    conn.AddDigitalOrderField("vpc_MerchTxnRef", merchTxnRef);
                    conn.AddDigitalOrderField("vpc_OrderInfo", string.Format("{0} {1}", "Order Info ", transactionId));
                    conn.AddDigitalOrderField("vpc_Amount", (amount * 100).ToString());
                    conn.AddDigitalOrderField("vpc_ReturnURL", string.Format("{0}?p={1}", Config.OnePayUrlReturn, HttpUtility.UrlEncode(paramReturnUrl)));
                    conn.AddDigitalOrderField("vpc_TicketNo", Utils.GetPublicIP());
                    // Chuyen huong trinh duyet sang cong thanh toan
                    string url = conn.Create3PartyQueryString();
                    return Redirect(url);
                }
                else
                {
                    Subscription subscription =
                            new SubscriptionBL().GetBySubscriptionID(reNewModel.SubscriptionId);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(Config.PayPalUrl);
                    sb.Append("?");
                    sb.Append(string.Format("cmd={0}", "_xclick"));
                    sb.Append(string.Format("&business={0}", HttpUtility.UrlEncode("contact@findartinfo.com")));
                    sb.Append(string.Format("&item_name={0}", HttpUtility.UrlEncode("Subscription for " + subscription.Title + " (Id: " + transactionId + ")")));
                    sb.Append(string.Format("&item_number={0}", "Signatures"));
                    sb.Append(string.Format("&amount={0}", amount.ToString()));
                    sb.Append(string.Format("&no_shipping={0}", "0"));
                    sb.Append(string.Format("&return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlReturn, paramReturnUrl))));
                    sb.Append(string.Format("&cancel_return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlCancel, paramReturnUrl))));
                    sb.Append(string.Format("&no_note={0}", "0"));
                    sb.Append(string.Format("&currency_code={0}", "USD"));
                    sb.Append(string.Format("&lc={0}", "GB"));
                    sb.Append(string.Format("&bn={0}", "PP-BuyNowBF"));
                    return Redirect(sb.ToString());
                }
            }
            //return View(InitializeReNew());
            //return Redirect("~/renew.html");
            return Redirect(string.Format("~/{0}/renew.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        public PageReNewModel InitializeRegisterAgain()
        {
            Account account = (Account)Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID];
            PageReNewModel reNewModel = new PageReNewModel();
            reNewModel.ListSubscription = new SubscriptionBL().GetAll();
            reNewModel.Email = account.Email;
            return reNewModel;
        }

        [CustomAuthorizePaidAttribute]
        [RestoreModelStateFromTempData]
        public ActionResult RegisterAgain()
        {
            return View(InitializeRegisterAgain());
        }

        [CustomAuthorizePaidAttribute]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [SetTempDataModelState]
        public ActionResult RegisterAgain(PageReNewModel reNewModel)
        {
            Account account = (Account)Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID];
            //id giao dich thanh toan            
            string merchTxnRef = Encrypt.MD5(Guid.NewGuid().ToString());
            double amount;
            long transactionId;
            int result;
            new TransactionLogBL().Insert(account.Id, reNewModel.SubscriptionId,
                reNewModel.TypePay, Constants.TypeTransactionPayMent.RegisterAgain, reNewModel.CouponCode, merchTxnRef, out amount, out transactionId, out result);
            if (result > 0)
            {
                string paramReturnUrl = Encrypt.EncodeTo64(Crypto.EncryptString("#36&()9KJHaq@!ad", merchTxnRef + "#" + transactionId + "#" + Constants.TypeTransactionPayMent.RegisterAgain));
                //chuyen giao dich sang ben onepay
                if (reNewModel.TypePay == Constants.TypePay.ONE_PAY)
                {
                    //chuyen giao dich sang ben onepay
                    VPCRequest conn = new VPCRequest(Config.OnePayVitualPaymentClientURL);
                    conn.SetSecureSecret(Config.OnePaySecretKey);
                    conn.AddDigitalOrderField("AgainLink", "http://onepay.vn");
                    conn.AddDigitalOrderField("Title", "Onepay Paygate");
                    conn.AddDigitalOrderField("vpc_Locale", "en");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
                    conn.AddDigitalOrderField("vpc_Version", 2.ToString());
                    conn.AddDigitalOrderField("vpc_Command", "pay");
                    conn.AddDigitalOrderField("vpc_Merchant", Config.OnePayMerchantId);
                    conn.AddDigitalOrderField("vpc_AccessCode", Config.OnePayAccessCode);
                    conn.AddDigitalOrderField("vpc_MerchTxnRef", merchTxnRef);
                    conn.AddDigitalOrderField("vpc_OrderInfo", string.Format("{0} {1}", "Order Info ", transactionId));
                    conn.AddDigitalOrderField("vpc_Amount", (amount * 100).ToString());
                    conn.AddDigitalOrderField("vpc_ReturnURL", string.Format("{0}?p={1}", Config.OnePayUrlReturn, HttpUtility.UrlEncode(paramReturnUrl)));
                    conn.AddDigitalOrderField("vpc_TicketNo", Utils.GetPublicIP());
                    // Chuyen huong trinh duyet sang cong thanh toan
                    string url = conn.Create3PartyQueryString();
                    return Redirect(url);
                }
                else
                {
                    Subscription subscription =
                            new SubscriptionBL().GetBySubscriptionID(reNewModel.SubscriptionId);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(Config.PayPalUrl);
                    sb.Append("?");
                    sb.Append(string.Format("cmd={0}", "_xclick"));
                    sb.Append(string.Format("&business={0}", HttpUtility.UrlEncode("contact@findartinfo.com")));
                    sb.Append(string.Format("&item_name={0}", HttpUtility.UrlEncode("Subscription for " + subscription.Title + " (Id: " + transactionId + ")")));
                    sb.Append(string.Format("&item_number={0}", "Signatures"));
                    sb.Append(string.Format("&amount={0}", amount.ToString()));
                    sb.Append(string.Format("&no_shipping={0}", "0"));
                    sb.Append(string.Format("&return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlReturn, paramReturnUrl))));
                    sb.Append(string.Format("&cancel_return={0}", HttpUtility.UrlEncode(string.Format("{0}?p={1}", Config.PayPalUrlCancel, paramReturnUrl))));
                    sb.Append(string.Format("&no_note={0}", "0"));
                    sb.Append(string.Format("&currency_code={0}", "USD"));
                    sb.Append(string.Format("&lc={0}", "GB"));
                    sb.Append(string.Format("&bn={0}", "PP-BuyNowBF"));
                    return Redirect(sb.ToString());
                }
            }
            //return View(InitializeRegisterAgain());
            //return Redirect("~/register-again.html");
            return Redirect(string.Format("~/{0}/register-again.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        public ActionResult OnePayResponse(string p)
        {
            try
            {
                string paramReturnUrl = Crypto.DecryptString("#36&()9KJHaq@!ad", Encrypt.DecodeFrom64(p));
                string merchTxnRefOfReturnUrl = paramReturnUrl.Split('#')[0];
                long transactionId = Convert.ToInt64(paramReturnUrl.Split('#')[1]);
                int typeTransactionPayment = Convert.ToInt32(paramReturnUrl.Split('#')[2]);
                string SECURE_SECRET = Config.OnePaySecretKey;
                string hashvalidateResult = "";
                // Khoi tao lop thu vien
                VPCRequest conn = new VPCRequest("http://onepay.vn");
                conn.SetSecureSecret(SECURE_SECRET);
                // Xu ly tham so tra ve va kiem tra chuoi du lieu ma hoa
                hashvalidateResult = conn.Process3PartyResponse(HttpContext.Request.QueryString);
                // Lay gia tri tham so tra ve tu cong thanh toan
                string vpc_TxnResponseCode = conn.GetResultField("vpc_TxnResponseCode", "Unknown");
                string amount = conn.GetResultField("vpc_Amount", "Unknown");
                string localed = conn.GetResultField("vpc_Locale", "Unknown");
                string command = conn.GetResultField("vpc_Command", "Unknown");
                string version = conn.GetResultField("vpc_Version", "Unknown");
                string cardType = conn.GetResultField("vpc_Card", "Unknown");
                string orderInfo = conn.GetResultField("vpc_OrderInfo", "Unknown");
                string merchantID = conn.GetResultField("vpc_Merchant", "Unknown");
                string authorizeID = conn.GetResultField("vpc_AuthorizeId", "Unknown");
                string merchTxnRef = conn.GetResultField("vpc_MerchTxnRef", "Unknown");
                string transactionNo = conn.GetResultField("vpc_TransactionNo", "Unknown");//ngan hang trả ra
                string acqResponseCode = conn.GetResultField("vpc_AcqResponseCode", "Unknown");
                string txnResponseCode = vpc_TxnResponseCode;
                string message = conn.GetResultField("vpc_Message", "Unknown");

                if (merchTxnRefOfReturnUrl == merchTxnRef)
                {
                    //Kiem tra xem co ton tai transaction dang o trang thai chua kich hoat
                    TransactionLog transactionLog = new TransactionLogBL().GetById(transactionId);
                    if (transactionLog.Status == Constants.TranctionLogStatus.START && transactionLog.MerchTxnRef == merchTxnRef)
                    {
                        Account account = new AccountBL().GetById(transactionLog.AccountId);
                        if (account != null)
                        {                                                        
                            //cap nhat lai trang thai cua giao dich
                            if (typeTransactionPayment == Constants.TypeTransactionPayMent.Register)
                            {
                                //string tokenKey = Encrypt.MD5(Guid.NewGuid().ToString());
                                //new AccountTokenBL().Insert(new AccountToken { AccountId = account.Id, Status = Constants.StatusAccountTokenKey.NOT_ACTIVE, TokenKey = tokenKey });
                                //string subject = "Active Account";
                                //string activeKey = Encrypt.EncodeTo64(Crypto.EncryptString("#36&()9KJHaq@!ad", string.Format("{0}#{1}#{2}#{3}", transactionId, tokenKey, merchTxnRef, transactionNo)));
                                //string content = string.Format("Please click to <a href='http://art.hanoiservice.com/Account/Active?activeKey="+ activeKey +"'>active account</a>");                                
                                //Utils.SendMail(Config.FromEmail, Config.UserEmail, Config.PassEmail, account.Email,
                                    //account.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                                
                                new TransactionLogBL().Approve(transactionId,
                                                                (txnResponseCode.Trim() == "0" && hashvalidateResult == "CORRECTED") ? Constants.TranctionLogStatus.SUCCESS : Constants.TranctionLogStatus.ERROR,
                                                                string.Format("{0}#{1}#{2}", transactionNo, txnResponseCode, message));                                   
                            }
                            else
                            {
                                if (typeTransactionPayment == Constants.TypeTransactionPayMent.RegisterAgain)
                                {
                                    new TransactionLogBL().ApproveRegisterAgain(transactionId,
                                                                (txnResponseCode.Trim() == "0" && hashvalidateResult == "CORRECTED") ? Constants.TranctionLogStatus.SUCCESS : Constants.TranctionLogStatus.ERROR,
                                                                string.Format("{0}#{1}#{2}", transactionNo, txnResponseCode, message)); 
                                }
                                else
                                {
                                    new TransactionLogBL().ApproveAccountReNew(transactionLog.Id, transactionLog.AccountId, transactionLog.SubscriptionId,
                                                                (txnResponseCode.Trim() == "0" && hashvalidateResult == "CORRECTED") ? Constants.TranctionLogStatus.SUCCESS : Constants.TranctionLogStatus.ERROR,
                                                                string.Format("{0}#{1}#{2}", transactionNo, txnResponseCode, message)); 
                                }                                                                   
                            }
                            if (hashvalidateResult == "CORRECTED" && txnResponseCode.Trim() == "0")
                            {
                                //send email
                                string subject = "Access to FindArtInfo.com";
                                string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                                Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, account.Email,
                                                        account.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                                //end
                                return RedirectToAction("PaymentSuccess");
                            }
                            else
                            {
                                return RedirectToAction("PaymentError");
                            } 
                                                                                                                                           
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            catch
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult PayPalResponse(string p)
        {
            string paramReturnUrl = Crypto.DecryptString("#36&()9KJHaq@!ad", Encrypt.DecodeFrom64(p));
            string merchTxnRefOfReturnUrl = paramReturnUrl.Split('#')[0];
            long transactionId = Convert.ToInt64(paramReturnUrl.Split('#')[1]);
            int typeTransactionPayment = Convert.ToInt32(paramReturnUrl.Split('#')[2]);
            //Kiem tra xem co ton tai transaction dang o trang thai chua kich hoat
            TransactionLog transactionLog = new TransactionLogBL().GetById(transactionId);
            if (merchTxnRefOfReturnUrl == transactionLog.MerchTxnRef)
            {
                if (transactionLog.Status == Constants.TranctionLogStatus.START)
                {
                    Account account = new AccountBL().GetById(transactionLog.AccountId);
                    if (account != null)
                    {
                        //neu ton tai account va trang thai chua kich hoat thi gui mail kick hoat
                        if (typeTransactionPayment == Constants.TypeTransactionPayMent.Register)
                        {

                            new TransactionLogBL().Approve(transactionId, Constants.TranctionLogStatus.SUCCESS,
                                                           string.Empty);
                            //send email
                            string subject = "Access to FindArtInfo.com";
                            string content =
                                string.Format(
                                    "Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password. You would run the risk of disabling your account if any invalid login.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>",
                                    account.LastName, account.Email, account.PassWord);
                            Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, account.Email,
                                           account.Email, Config.EmailCC, subject, content, Config.Host,
                                           Convert.ToInt32(Config.Port));
                            //end
                            return RedirectToAction("PaymentSuccess");
                        }
                        else
                        {
                            if (typeTransactionPayment == Constants.TypeTransactionPayMent.RegisterAgain)
                            {
                                new TransactionLogBL().ApproveRegisterAgain(transactionId,
                                                                            Constants.TranctionLogStatus.SUCCESS,
                                                                            string.Empty);
                                //send email
                                string subject = "Access to FindArtInfo.com";
                                string content =
                                    string.Format(
                                        "Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>",
                                        account.LastName, account.Email, account.PassWord);
                                Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail,
                                               account.Email,
                                               account.Email, Config.EmailCC, subject, content, Config.Host,
                                               Convert.ToInt32(Config.Port));
                                //end
                                return RedirectToAction("PaymentSuccess");
                            }
                            else
                            {
                                new TransactionLogBL().ApproveAccountReNew(transactionLog.Id, transactionLog.AccountId,
                                                                           transactionLog.SubscriptionId,
                                                                           Constants.TranctionLogStatus.SUCCESS,
                                                                           string.Empty);
                                //send email
                                string subject = "Access to FindArtInfo.com";
                                string content =
                                    string.Format(
                                        "Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>",
                                        account.LastName, account.Email, account.PassWord);
                                Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail,
                                               account.Email,
                                               account.Email, Config.EmailCC, subject, content, Config.Host,
                                               Convert.ToInt32(Config.Port));
                                //end
                                return RedirectToAction("PaymentSuccess");
                            }

                        }
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return RedirectToAction("Index", "Home");
        }

        public ActionResult PaymentCancel()
        {
            return View();
        }

        public ActionResult PaymentSuccess()
        {           
            return View();
        }

        public ActionResult PaymentError()
        {
            return View();
        }

        public ActionResult ReNewSuccess()
        {
            return View();
        }

        public ActionResult Active(string activeKey)
        {
            try
            {
                //string decryptActiveKey = Crypto.DecryptString("#36&()9KJHaq@!ad", Encrypt.DecodeFrom64(activeKey));
                //long transactionId = Convert.ToInt64(decryptActiveKey.Split('#')[0]);
                //string tokenKey = decryptActiveKey.Split('#')[1];
                //string merchTxnRef = decryptActiveKey.Split('#')[2];
                //int result = -1;
                //new AccountBL().ActiveAccount(transactionId, tokenKey, merchTxnRef, out result);
                //if (result < 0)
                //{                    
                //    return RedirectToAction("ActiveAccountError");
                //}
                return RedirectToAction("ActiveAccountSuccess");
            }
            catch
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult ActiveAccountSuccess()
        {
            return View();
        }

        public ActionResult ActiveAccountError()
        {
            return View();
        }

        [CustomAuthorizeAttribute]
        public ActionResult Detail()
        {
            PageAccountDetailModel model = new PageAccountDetailModel();
            Account account = (Account) Session[Constants.SessionKey.SESSION_USER_LOGIN];
            DateTime dateTimeNow = new CommonBL().GetDateTimeNow();
            TimeSpan timeSpan = Convert.ToDateTime(account.EndDate) - dateTimeNow;

            Country country = new BusinessLayer.RegInfo.CountryBL().GetById(account.CountryId);
            model.Country = country.CountryName;
            model.Email = account.Email;
            model.Expires = timeSpan.Days;
            model.FirstName = account.FirstName;
            model.LastName = account.LastName;
            model.RegistrationDate = account.CreateDate;
            TransactionLog transactionLogsTop = new TransactionLogBL().GetByAccountId(account.Id).FirstOrDefault();
            if(transactionLogsTop != null)
            {
                model.Subscription = new SubscriptionBL().GetBySubscriptionID(transactionLogsTop.SubscriptionId).NumberOfDays.ToString();
            }

            return View(model);
        }

        public ActionResult LogOut()
        {
            Session.Abandon();
            Session.Clear();
            return Redirect(string.Format("~/{0}/home.html", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
        }

        public ActionResult Members(string k)
        {
            PageDoNotSendEmailAdvertiseModel model = new PageDoNotSendEmailAdvertiseModel();
            model.Key = k;
            model.Title = "Thanks you for your information. Please click \"Yes\" to confirm unsubscribe";
            model.Status = false;
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Members(PageDoNotSendEmailAdvertiseModel model)
        {
            string email = Crypto.DecryptString("#39&()9TJHaq@!fg", Encrypt.DecodeFrom64(model.Key));
            AccountBL accountBl = new AccountBL();
            accountBl.InsertBlackList(email);
            return View(new PageDoNotSendEmailAdvertiseModel { Key = model.Key, Title = "Unsubscribe successful!", Status = true });
        }
    }
}
